package cn.gailvlun.gll.presentation.wish.accepter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ObservableField;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;

import java.util.Date;
import java.util.HashMap;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.chatlib.db.ChatDB2;
import cn.gailvlun.gll.chatlib.message.Message;
import cn.gailvlun.gll.databinding.ActivityAcceptedWishBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.base.Profile;
import cn.gailvlun.gll.net.wish.OperationRecordReq;
import cn.gailvlun.gll.net.wish.Wish;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.chat.ChatActivity;
import cn.gailvlun.gll.presentation.wish.maker.MakeWishActivity;
import cn.gailvlun.gll.presentation.wish.maker.WishExplainActivity;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.ReportUtil;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.SPUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.realm.Realm;


public class AcceptedWishActivity extends BaseActivity {

    private ActivityAcceptedWishBinding mBinding;
    private int mWishId;
    private Presenter mPresenter;

    public static void openActivity(Context context) {
        context.startActivity(new Intent(context, AcceptedWishActivity.class));
    }

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_accepted_wish);
        mPresenter = new Presenter();
        mBinding.setPresenter(mPresenter);
    }

    @Override
    protected void createHandler() {
        mBinding.navigationBar.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.navigationBar.setOnMenuClickListener(new NavigationBarView.OnMenuClickListener() {
            @Override
            public void onMenuClick(NavigationBarView nb) {
                new ReportUtil(mContext).show();
            }
        });
    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        getWishRecord();
    }

    private void getWishRecord() {
        final Dialog dialog = DialogUtil.showIndeterminate(mContext);
        HttpMethods.getWishService()
                .getWishRecord()
                .compose(RxUtil.<Wish>applyScheduler())
                .compose(this.<Wish>bindToLifecycle())
                .subscribe(new HttpSubscriber<Wish>() {
                    @Override
                    protected void onSuccess(Wish response) {
                        dialog.dismiss();
                        if (response != null) {
                            mPresenter.stateObservableField.set(State.HAS_WISH);
                            mPresenter.wishObservableField.set(response);
                            mWishId = response.getId();
                        }

                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable Wish response, int code) {
                        dialog.dismiss();
                        if (code == 400) {
                            
                            mPresenter.stateObservableField.set(State.NO_WISH);

                        } else if (code == 401) {
                            
                            mPresenter.stateObservableField.set(State.USE_UP_WISH);
                        } else {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    }
                });
    }

    public class Presenter {
        public ObservableField<State> stateObservableField = new ObservableField<>(State.NONE);
        public ObservableField<Wish> wishObservableField = new ObservableField<>();
        public ObservableField<String> errMsgObservableField = new ObservableField<>("");

        public void onRefuse() {
            final OperationRecordReq req = new OperationRecordReq();
            req.setWish_id(mWishId);
            req.setAction("refuse");
            View view=DataBindingUtil.inflate(LayoutInflater.from(mContext),R.layout.dialog_refuse,null,false).getRoot();
            final AlertDialog dialog = new AlertDialog.Builder(mContext)
                    .setView(view)
                    .create();
            dialog.show();
            view.findViewById(R.id.bt_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            view.findViewById(R.id.bt_ok).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                    HttpMethods.getWishService()
                            .refuse(req)
                            .compose(RxUtil.<HashMap>applyScheduler())
                            .subscribe(new HttpSubscriber<HashMap>() {
                                @Override
                                protected void onSuccess(HashMap response) {
                                    dialog.dismiss();
                                    String detail = (String) response.get("detail");
                                    ToastUtil.showShort(detail);
                                    getWishRecord();
                                }

                                @Override
                                protected void onFailure(String errMsg, @Nullable HashMap response, int code) {
                                    dialog.dismiss();
                                    DialogUtil.showError(mContext, errMsg);
                                }
                            });
                }
            });
        }

        public void onAccept() {
            OperationRecordReq req = new OperationRecordReq();
            req.setWish_id(mWishId);
            req.setAction("accept");
            HttpMethods.getWishService()
                    .accept(req)
                    .compose(RxUtil.<Wish>applyScheduler())
                    .subscribe(new HttpSubscriber<Wish>() {
                        @Override
                        protected void onSuccess(Wish wish) {
                            ToastUtil.showShort("领取成功");
                            Profile accepter = wish.getAccepter();
                            Profile owner = wish.getOwner();

                            Realm realm = Realm.getInstance(ChatDB2.INSTANCE.getConfiguration());
                            realm.beginTransaction();
                            realm.insertOrUpdate(owner);

                            Message hisMsg = Message.text("嗨，很高兴认识你哦！\n下面是我许的愿望哦，希望你能帮我完成:\n" + wish.getText(), new Date(), owner, "user:" + owner.getId());
                            realm.insertOrUpdate(hisMsg);

                            Message myMsg = Message.text("久等了，我是你的救世主~ \n我来帮你实现愿望啦，请多多指教哦！", new Date(), accepter, "user:" + owner.getId());
                            realm.insertOrUpdate(myMsg);

                            realm.commitTransaction();
                            realm.close();
                            ChatActivity.openActivity(mContext, "user:" + owner.getId());

                            finish();
                        }

                        @Override
                        protected void onFailure(String errMsg, @Nullable Wish response, int code) {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    });

        }

        public void onMakeWish() {
            boolean isWishRead = SPUtil.getBoolean(SPUtil.USER, "wishExplain");
            if (isWishRead) {
                MakeWishActivity.openActivity(mContext);
            } else {
                WishExplainActivity.openActivity(mContext);
            }
            finish();

        }

    }


    public enum State {
        NONE,
        HAS_WISH,
        NO_WISH,
        USE_UP_WISH
    }
}
